package com.base.invoke.okhttp.executer;

import java.security.SecureRandom;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.base.invoke.okhttp.handle.OkHttpClientBuilder;
import com.base.invoke.okhttp.handle.GetBuilder;
import com.base.invoke.okhttp.handle.PostBuilder;
import com.base.invoke.okhttp.handle.PutBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.base.invoke.okhttp.ssl.X509TrustManager;

/**
 * @desc okhttp执行器
 * @author coolpig
 * @date 2019-08-28
 */
public class OkHttpClient {
	//
	public static Logger logger = LoggerFactory.getLogger(OkHttpClient.class);
	//
	public static final String VERSION="1.6";
	//
	private static HttpClient httpClient = new HttpClient(getDefaultOkHttpClient());
	//
	private static okhttp3.OkHttpClient getDefaultOkHttpClient() {
		okhttp3.OkHttpClient.Builder builder = new okhttp3.OkHttpClient().newBuilder();
		//
		final javax.net.ssl.X509TrustManager trustManager = new X509TrustManager();
		SSLSocketFactory sslSocketFactory=null;
		try {
			SSLContext sslContext = SSLContext.getInstance("SSL");
			sslContext.init(null, new TrustManager[] { trustManager },new SecureRandom());
			sslSocketFactory = sslContext.getSocketFactory();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return builder.sslSocketFactory(sslSocketFactory, trustManager).hostnameVerifier(new HostnameVerifier() {
			@Override
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		}).build();
	}
	//
	public static OkHttpClientBuilder newBuilder(){
		return new OkHttpClientBuilder(httpClient.getOkHttpClient());
	}
	//
	public static OkHttpClientBuilder newBuilder(okhttp3.OkHttpClient client){
		return new OkHttpClientBuilder(client);
	}
	//
	public static GetBuilder get() {
		return httpClient.get();
	}
	//
	public static PostBuilder post() {
		return httpClient.post();
	}
	//
	public static PutBuilder put() {
		return httpClient.put();
	}
	//
	/**
	 * @return the httpClient
	 */
	public static HttpClient getHttpClient() {
		return httpClient;
	}
	/**
	 * @param httpClient the httpClient to set
	 */
	public static void setHttpClient(HttpClient httpClient) {
		OkHttpClient.httpClient = httpClient;
	}
}
